package com.demoworld.rocketmq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.List;

/**
 * Description
 * <p>
 * </p>
 * DATE 2018/8/1.
 *
 * @author liwei5.
 */
public class RocketmqConsumerInfo {
    private final DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group1");

    public RocketmqConsumerInfo() throws MQClientException {
        consumer.setNamesrvAddr(Application.producerInfo.producer.getNamesrvAddr());
        consumer.setInstanceName("consumer_group_1");
        consumer.subscribe(Application.topic, "*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                if (msgs == null || msgs.isEmpty()) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                for (MessageExt item : msgs) {
                    System.out.println("收到消息: " + new String(item.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

    }

    public void startUp() throws MQClientException {
        consumer.start();
    }
}
